package com.wzcl.app.handler;

import com.wzcl.app.dao.model.Activity;
import com.wzcl.app.dao.model.ActivityGroup;
import com.wzcl.app.dao.model.Orders;
import com.wzcl.app.model.common.WZCL;
import com.wzcl.app.service.LiveRoomService;
import com.wzcl.app.service.common.MyPayService;
import com.wzcl.app.service.common.PayServiceFactory;
import com.wzcl.app.service.impl.*;
import com.wzcl.app.utils.SpringUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.List;

@Log4j2
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private LiveRoomService liveRoomService;


    public RedisKeyExpirationListener(RedisMessageListenerContainer container) {
        super(container);
    }

    /**
     * 针对redis数据失效事件，进行数据处理
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String key=message.toString();//生效的key
        if (key!=null){
            //从失效key中筛选代表订单失效的key
            if(key.startsWith(LiveRoomServiceImpl.STATE_KEY)){
                //开始直播
                String roomNub = key.substring(LiveRoomServiceImpl.STATE_KEY.length());
                liveRoomService.onLive(roomNub);
            }else if(key.startsWith(LiveRoomServiceImpl.END_KEY)){
                //结束直播
                String roomNub = key.substring(LiveRoomServiceImpl.END_KEY.length());
                liveRoomService.offLive(roomNub);
            }else if(key.startsWith(ActivityServiceImpl.ON_LINE_KEY)){
                //活动上线
                String activityId = key.substring(ActivityServiceImpl.ON_LINE_KEY.length());
                ActivityServiceImpl activityService = (ActivityServiceImpl) SpringUtil.getBean("activityServiceImpl");
                Activity activity = activityService.getActivityById(Integer.valueOf(activityId));
                activityService.onlineActivity(activity);
            }else if(key.startsWith(ActivityServiceImpl.OFF_LINE_KEY)){
                //活动下线
                String activityId = key.substring(ActivityServiceImpl.OFF_LINE_KEY.length());
                ActivityServiceImpl activityService = (ActivityServiceImpl) SpringUtil.getBean("activityServiceImpl");
                Activity activity = activityService.getActivityById(Integer.valueOf(activityId));
                activityService.offlineActivity(activity);
            }else if(key.startsWith(ActivityGroupServiceImpl.GROUP_EXPIRED_KEY)){
                //开团的到期了
                String groupId = key.substring(ActivityGroupServiceImpl.GROUP_EXPIRED_KEY.length());
                ActivityGroupServiceImpl groupService = (ActivityGroupServiceImpl) SpringUtil.getBean("activityGroupServiceImpl");
                ActivityGroup group = groupService.getAndCheckById(Integer.valueOf(groupId));
                if(WZCL.GROUP_STATE.PROCESSING.equals(group.getGroupState())){
                    String createFrom = new StringBuffer(OrderServiceImpl.GROUP_TYPE_KEY).append("_")
                            .append(group.getCommodityId()).append("_")
                            .append(group.getActivityId())
                            .append(":")
                            .append("%")
                            .toString();
                    OrderServiceImpl orderService = (OrderServiceImpl) SpringUtil.getBean("orderServiceImpl");
                    //TODO 支付记录哈哈哈
                    //PayRecordServiceImpl payRecordService = (PayRecordServiceImpl) SpringUtil.getBean("payRecordServiceImpl");
                    List<Orders> ordersList = orderService.findAllByCreateFromLike(createFrom);
                    ordersList.stream().filter(orders -> orders.getCreateFrom().contains(String.format("\"%s\":%d", OrderServiceImpl.GROUP_PARAMETER_GROUP_ID, group.getId())))
                            .forEach(orders -> {
                                //取消拼团订单(不删除订单,先退款)
                                //TODO 支付记录哈哈哈
                                /*PayRecord payRecord = payRecordService.getAndCheckByOrderNo(orders.getNo());
                                MyPayService myPayService = PayServiceFactory.makePayService(payRecord.getPayType());
                                myPayService.refund(payRecord);*/
                            });
                    group.setGroupState(WZCL.GROUP_STATE.EXPIRED);
                    groupService.save(group);
                }
            }
        }
    }

}
